import { _decorator, Component, Node, AudioClip, AudioSource, resources, director } from 'cc';
const { ccclass, property } = _decorator;

// 音频资源枚举
export enum SoundType {
    Coin = 'coin',
    Hit = '击中',
    Explosion = '爆破',
    Bomb = '爆炸',
    ButtonClick = 'click',
    Background = 'music',
    Waring = 'waring',
    GetItem = '获得道具',
    // ... 添加更多音效
}

@ccclass('SoundManager')
export class SoundManager extends Component {
    private static _instance: SoundManager = null;
    private audioSources: Map<string, AudioSource> = new Map();
    private audioClips: Map<string, AudioClip> = new Map();
    private playingAudioSources: Map<string, AudioSource[]> = new Map();
    private isInitialized: boolean = false;

    // 单例访问器
    public static get instance(): SoundManager {
        if (!this._instance) {
            const node = new Node('SoundManager');
            node.parent = director.getScene();  // 确保节点被添加到场景中
            this._instance = node.addComponent(SoundManager);
            // 设置为不销毁
            node._persistNode = true;
            // 立即初始化
            this._instance.initialize();
        }
        return this._instance;
    }

    // 初始化加载所有音频资源
    private initialize() {
        if (this.isInitialized) return;
        // 预加载所有音频资源
        resources.loadDir('Sound', AudioClip, (err, clips) => {
            if (err) {
                console.error('Failed to load audio clips:', err);
                return;
            }

            clips.forEach(clip => {
                const name = clip.name;
                this.audioClips.set(name, clip);
                // 为每个音效创建一个 AudioSource
                const audioSource = this.node.addComponent(AudioSource);
                audioSource.clip = clip;
                this.audioSources.set(name, audioSource);
            });

            this.isInitialized = true;
            console.log('Audio system initialized');
        });
    }

    // 播放音效
    public playSound(type: SoundType, volume: number = 1.0, loop: boolean = false) {
        if (!this.isInitialized || !this.isValid) {
            console.warn('Sound system not initialized or invalid');
            return null;
        }

        const audioClip = this.audioClips.get(type);
        if (!audioClip) {
            console.warn(`Sound ${type} not found`);
            return null;
        }

        // 创建新的 AudioSource
        const newAudioSource = this.node.addComponent(AudioSource);
        newAudioSource.clip = audioClip;
        newAudioSource.volume = volume;
        newAudioSource.loop = loop;
        newAudioSource.play();

        // 添加到播放列表
        if (!this.playingAudioSources.has(type)) {
            this.playingAudioSources.set(type, []);
        }
        this.playingAudioSources.get(type).push(newAudioSource);

        // 非循环音效的清理
        if (!loop) {
            const duration = audioClip.getDuration();
            this.scheduleOnce(() => {
                if (this.isValid && newAudioSource.isValid) {
                    this.cleanupAudioSource(type, newAudioSource);
                }
            }, duration);
        }

        return newAudioSource;
    }

    // 停止特定音效
    public stopSound(type: SoundType) {
        if (!this.isValid) return;

        const playingSources = this.playingAudioSources.get(type);
        if (playingSources) {
            playingSources.forEach(source => {
                if (source && source.isValid) {
                    source.stop();
                    source.destroy();
                }
            });
            this.playingAudioSources.set(type, []);
        }
    }

    // 停止所有音效
    public stopAllSounds() {
        if (!this.isValid) return;

        this.playingAudioSources.forEach((sources, type) => {
            sources.forEach(source => {
                if (source && source.isValid) {
                    source.stop();
                    source.destroy();
                }
            });
            this.playingAudioSources.set(type, []);
        });
    }

    // 清理单个AudioSource
    private cleanupAudioSource(type: SoundType, audioSource: AudioSource) {
        if (!this.isValid || !audioSource || !audioSource.isValid) return;

        const sources = this.playingAudioSources.get(type);
        if (sources) {
            const index = sources.indexOf(audioSource);
            if (index !== -1) {
                sources.splice(index, 1);
            }
        }
        audioSource.destroy();
    }

    // 设置特定音效音量
    public setSoundVolume(type: SoundType, volume: number) {
        const audioSource = this.audioSources.get(type);
        if (audioSource) {
            audioSource.volume = volume;
        }
    }

    // 设置所有音效音量
    public setAllSoundVolume(volume: number) {
        this.audioSources.forEach(source => {
            source.volume = volume;
        });
    }
}

